package com.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import com.graph.Graph;

public class Analyzer {
	
	public String sentence;
	
	public List<String> tokens;
	
	public List<String> schemas;
	
	public HashMap<String, List<String>> labelToAttrs;
	
	public HashMap<String[], String[]> references;
	
	public Analyzer(String sentence) {
		this.sentence = sentence;
		schemas = new ArrayList<String>();
		labelToAttrs = new HashMap<String, List<String>>();
		references = new HashMap<String[], String[]>();
	}
	
	public void analyze() {
		sentence = sentence.replace(",", " ");
		sentence = sentence.replace("  ", " ");
		
		// Generate tokens
		tokens = new ArrayList<String>(Arrays.asList(sentence.split(" ")));
		
		// Analyze Schemas
		for (int i = tokens.indexOf("FROM") + 1; i < tokens.size(); i++) {
			if (tokens.get(i).equals("WHERE")) {
				break;
			}
			schemas.add(tokens.get(i));
		}
		
		// Analyze Attributes
		for (String t : tokens) {
			if (t.contains(".")) {
				String[] kv = t.split("\\.");
				if (labelToAttrs.containsKey(kv[0])) {
					if (!labelToAttrs.get(kv[0]).contains(kv[1])) {
						labelToAttrs.get(kv[0]).add(kv[1]);
					}
				} else {
					labelToAttrs.put(kv[0], new ArrayList<String>() {{add(kv[1]);}});
				}
			}
		}
		
		// Analyze references
		for (int i = 0; i < tokens.size(); i++) {
			if (tokens.get(i).equals("=")) {
				String[] kv1 = tokens.get(i - 1).split("\\.");
				String[] kv2 = tokens.get(i + 1).split("\\.");
				references.put(kv1, kv2);
			}
		}
	}
	
	public Graph genQueryGraph() {
		return new Graph(labelToAttrs, references);	
	}
}
